//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/course/course_chapter_model.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/home/recommend_expandable_widget.dart';

/// 课程目录页面显示
class CatalogPage extends StatefulWidget {
  /// 栏目id
  final String columnId;

  const CatalogPage({
    super.key,
    required this.columnId,
  });

  @override
  State<CatalogPage> createState() => _CatalogPageState();
}

class _CatalogPageState extends State<CatalogPage> {
  late BuildContext _context;

  /// 加载数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 目录相关数据
  late List<CourseChapterModel> _list;

  /// 第一次执行方法
  late bool _init;

  @override
  void initState() {
    super.initState();
    debugPrint("catalogPage 页面 -> initSate 方法执行 ===> ");
    debugPrint("");
    _list = [];
    _init = true;
    _futureInit = _initData();
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("catalogPage 页面 -> dispose 方法执行 ===> ");
    debugPrint("");
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("catalogPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: context, msg: map["msg"]);
            });
          }
          if (_init) {
            // 页面创建完成将_init转为false,只执行一次
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              _init = false;
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      DataModel dataModel = dataUtilComm.dataModel;
      _list = await CourseDao.listByColumn(
        industryCode: dataModel.industryId,
        examId: dataModel.examId,
        categoryId: dataModel.categoryId,
        columnId: widget.columnId,
      );
      map["suc"] = true;
    } catch (e) {
      debugPrint("catalogPage 页面 -> 初始化发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("catalogPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示
  Widget _content() {
    return Container(
      padding: EdgeInsets.all(16),
      child: _listItem(),
    );
  }

  /// list内显示
  _listItem() {
    if (_list.isEmpty) {
      return showNoData();
    } else {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: _list.length,
        ),
      );
    }
  }

  /// 滑动具体实现
  Widget? _itemBuilder(BuildContext context, int index) {
    if (index < _list.length) {
      CourseChapterModel model = _list[index];
      return RecommendExpandableWidget(
        model: model,
        columnId: widget.columnId,
        free: model.free!,
        opening: index == 0 && _init,
        init: _init,
        courseDetail: true,
      );
    } else {
      return null;
    }
  }
}
